import { Request, Response, NextFunction } from "express";
import { connection } from "@/services/database";
import { checkIsAdmin, checkIsAgency, checkIsStudentBelongUser, checkIsTeacher, generateLimitFields, generateWhereFields } from "@/utils/sql";

interface Params {
	user_id?: number;
	page_number: number;
	page_size: number;
}
export default async (request: Request, response: Response, next: NextFunction) => {
	try {
		const params = request.query as unknown as Params;
		const callerId = response.locals.user.id;
		const isAdmin = await checkIsAdmin(callerId);
		if (params.user_id && callerId != params.user_id && !(await checkIsStudentBelongUser(callerId, params.user_id)) && !isAdmin) throw new Error("无权操作");
		if (isAdmin) {
			const [result] = await connection.execute(`
				SELECT signup_id, user_id, parent_phone_number, origin, party_affiliation, major, awards, personal_evaluation, personal_intentions
				FROM signup
				${generateWhereFields({ user_id: params.user_id })}
				${generateLimitFields(params.page_number, params.page_size)}
			`);
			const [totalResult] = (await connection.execute(`
				SELECT COUNT(*) AS total FROM signup
				${generateWhereFields({ user_id: params.user_id })}
			`)) as any;
			response.json({ data: { list: result, total: totalResult[0]?.total || 0 }, message: "成功" });
		} else if ((await checkIsTeacher(callerId)) || (await checkIsAgency(callerId))) {
			const [result] = (await connection.execute(`
				SELECT signup.signup_id, signup.user_id, signup.parent_phone_number, signup.origin, signup.party_affiliation, signup.major, signup.awards, signup.personal_evaluation, signup.personal_intentions FROM signup
				INNER JOIN student ON student.user_id = signup.user_id
				INNER JOIN user ON user.phone_number = student.contact_phone_number
				${generateWhereFields({ "user.user_id": callerId, "signup.user_id": params.user_id })}
				${generateLimitFields(params.page_number, params.page_size)}
			`)) as any;
			const [totalResult] = (await connection.execute(`
				SELECT COUNT(*) AS total FROM signup
				INNER JOIN student ON student.user_id = signup.user_id
				INNER JOIN user ON user.phone_number = student.contact_phone_number
				${generateWhereFields({ "user.user_id": callerId, "signup.user_id": params.user_id })}
			`)) as any;
			response.json({ data: { list: result, total: totalResult[0]?.total || 0 }, message: "成功" });
		} else throw new Error("无权操作");
	} catch (error) {
		response.statusCode = 400;
		next(error);
	}
};
